package com.net.xpay.operator.secutiry;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.net.common.exception.BusinessException;
import com.net.common.web.CookieHelper;
import com.net.xpay.core.constant.OperatorUserWebConstant;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.helper.DomainHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author  on 07/02/2018.
 */
@Component
public class SecurityHelper {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private DomainHelper domainHelper;

    public void sendRestResult(HttpServletResponse response, Object object) {
        try {
            Preconditions.checkArgument(object != null);
            String json = objectMapper.writeValueAsString(object);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(json);
        } catch (Exception e) {
            throw new BusinessException(PoseidonErrorCode.BUSINESS_ERROR, "系统处理返回值错误");
        }
    }

    public void removeInvalidSessionCookie(HttpServletRequest request, HttpServletResponse response) {
        String cookieDomain = domainHelper.getCookieDomain(request);

        CookieHelper.deleteCookie(response, cookieDomain, "/", OperatorUserWebConstant.SESSION_COOKIE_NAME);
        CookieHelper.deleteCookie(response, cookieDomain, "/", OperatorUserWebConstant.REMEMBER_ME_COOKIE_NAME);
    }
}
